package com.nexgo.payment.trans.detail;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.nexgo.payment.R;
import com.nexgo.payment.constrant.SysConstant;
import com.nexgo.payment.constrant.TransType;
import com.nexgo.payment.databases.Repository;
import com.nexgo.payment.databases.TransRecord;
import com.nexgo.payment.fragment.ProgressDialogFragment;
import com.nexgo.payment.fragment.TextDialogFragment;
import com.nexgo.payment.trans.preauthcomvoid.PreAuthComVoidActivity;
import com.nexgo.payment.trans.salevoid.SaleVoidActivity;
import com.nexgo.payment.trans.scanvoid.ScanVoidActivity;
import com.nexgo.payment.ui.BaseActivity;
import com.nexgo.payment.util.StringUtils;
import com.nexgo.payment.util.ToastUtils;
import com.nexgo.payment.util.TransUtils;
import com.nexgo.payment.util.UIUtils;
import com.nexgo.payment.widget.ItemLinearLayout;
import com.nexgo.payment.widget.TitleBuilder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import java8.util.Optional;

/**
 * 交易详情界面
 *
 * @author 谭忠扬-YuriTam
 * @time 2017年8月14日
 */
public class TransDetailActivity extends BaseActivity implements TransDetailContract.View {
    private Logger log = LoggerFactory.getLogger(TransDetailActivity.class.getSimpleName());
    private static final int RESP_CODE = 2000;
    private static final String IS_CHANGE = "isChange";
    private static final String TRACE_NUM = "traceNum";

    @BindView(R.id.tv_amount)
    TextView tvAmount;
    @BindView(R.id.item_card_no)
    ItemLinearLayout mCardNo;
    @BindView(R.id.item_pay_code_no)
    ItemLinearLayout mPayCodeNo;
    @BindView(R.id.item_pay_trace_code)
    ItemLinearLayout mPayTraceCode;
    @BindView(R.id.item_date_time)
    ItemLinearLayout mTradeTime;
    @BindView(R.id.item_trade_type)
    ItemLinearLayout mTradeType;
    @BindView(R.id.item_merchant_no)
    ItemLinearLayout mMerchantNo;
    @BindView(R.id.item_terminal_no)
    ItemLinearLayout mTerminalNo;
    @BindView(R.id.item_refer_no)
    ItemLinearLayout mReferNo;
    @BindView(R.id.item_batch_no)
    ItemLinearLayout mBatchNo;
    @BindView(R.id.item_trace_num)
    ItemLinearLayout mTraceNum;
    @BindView(R.id.item_org_trace_num)
    ItemLinearLayout mOrgTraceNum;
    @BindView(R.id.item_op_no)
    ItemLinearLayout mOpNo;
    @BindView(R.id.btn_void)
    Button btnVoid;

    private TransDetailPresenter mPresenter;
    private ProgressDialogFragment mDialogFragment;
    private boolean hideVoidBtn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_trans_detail);
        ButterKnife.bind(this);
        initView();

        Bundle bundle = getIntent().getExtras();
        String traceNum = null;
        if (bundle != null){
            traceNum = bundle.getString(TRACE_NUM);
            hideVoidBtn = bundle.getBoolean("hideVoidBtn", false);
        }
        log.debug("交易流水号：{}", traceNum);
        new TransDetailPresenter(this, Repository.getInstance(), traceNum);
    }

    /**
     * 初始化视图
     */
    private void initView() {
        new TitleBuilder(this)
                .setExternalTitleBgRes(R.drawable.bg_blue_icon)
                .setLeftImage(R.drawable.arrow_icon)
                .setRightText(getString(R.string.re_print))
                .setTitleText(getString(R.string.trans_detail_title))
                .build();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mPresenter.start();
    }

    @OnClick({R.id.title_iv_left, R.id.title_tv_right, R.id.btn_void})
    public void onClicked(View view) {
        if (UIUtils.isDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.title_iv_left:
                quitDetail();
                break;
            case R.id.title_tv_right:
                mPresenter.startPrint();
                break;
            case R.id.btn_void:
                mPresenter.doVoidByTransType();
                break;
            default:
                break;
        }
    }

    @Override
    public void setPresenter(TransDetailPresenter presenter) {
        mPresenter = presenter;
    }

    @Override
    public void onTransReceived(TransRecord transRecord) {
        //交易金额
        tvAmount.setText(StringUtils.formatAmount(transRecord.getAmount(), SysConstant.FUND_DIGITS));
        //卡号
        Optional.ofNullable(transRecord.getPan())
                .filter(s -> !TextUtils.isEmpty(s))
                .ifPresent(s -> {
                    mCardNo.setVisibility(View.VISIBLE);
                    mCardNo.setRightText(TransUtils.maskPan(s));
                });
        //支付码号(扫码相关)
        Optional.ofNullable(transRecord.getPayCodeNo())
                .filter(s -> !TextUtils.isEmpty(s))
                .ifPresent(s -> {
                    mPayCodeNo.setVisibility(View.VISIBLE);
                    mPayCodeNo.setRightText(TransUtils.maskPan(s));
                });
        //付款凭证码（扫码相关）
        Optional.ofNullable(transRecord.getPayTraceCode())
                .filter(s -> !TextUtils.isEmpty(s))
                .ifPresent(s -> {
                    mPayTraceCode.setVisibility(View.VISIBLE);
                    mPayTraceCode.setRightText(s);
                });
        //交易时间
        mTradeTime.setRightText(StringUtils.formatDateTime(transRecord.getDate(), transRecord.getTime()));
        //交易类型
        TransType transType = TransType.values()[transRecord.getTransType()];
        mTradeType.setRightText(transType.getName());
        //消费、预授权完成交易可从交易详情界面直接发起撤销

        if(hideVoidBtn){
            btnVoid.setVisibility(View.INVISIBLE);
        }else{
           if (transType == TransType.SALE || transType == TransType.SCAN_SALE || transType == TransType.SCAN_ORDER || transType == TransType.AUTH_CM) {
               btnVoid.setVisibility(transRecord.getIsVoid() ? View.INVISIBLE :View.VISIBLE);
           }
        }
        //商户号
        mMerchantNo.setRightText(transRecord.getMerchantId());
        //终端号
        mTerminalNo.setRightText(transRecord.getTerminalId());
        //参考号
        mReferNo.setRightText(transRecord.getRefNum());
        //批次号
        mBatchNo.setRightText(transRecord.getBatchNum());
        //凭证号
        mTraceNum.setRightText(transRecord.getTraceNum());
        //源凭证号
        Optional.ofNullable(transRecord.getOrgTraceNum())
                .filter(s -> !TextUtils.isEmpty(s))
                .ifPresent(s -> {
                    mOrgTraceNum.setVisibility(View.VISIBLE);
                    mOrgTraceNum.setRightText(s);
                });
        //操作员号
        mOpNo.setRightText(String.format(SysConstant.LOCALE, "%02d", transRecord.getOperator()));
    }

    @Override
    public void showSaleVoid(String traceNum) {
        startActivity(SaleVoidActivity.newInstance(this, traceNum));
    }

    @Override
    public void showScanSaleVoid(String traceCode) {
        startActivity(ScanVoidActivity.newInstance(this, traceCode));
    }

    @Override
    public void showAuthComVoid(String traceNum) {
        startActivity(PreAuthComVoidActivity.newInstance(this, traceNum));
    }

    @Override
    public void showTransNotExist() {
        ToastUtils.showToast(getString(R.string.trace_num_not_exsit));
    }

    @Override
    public void showNoTransRecord() {
        ToastUtils.showToast(getString(R.string.has_no_trans_record));
        if (mPresenter.isAutoPrint()) finish();
    }

    @Override
    public void showErrorTraceNum() {
        ToastUtils.showToast(getString(R.string.err_trace_num));
    }

    @Override
    public void showPrintInitErr() {
        ToastUtils.showToast(getString(R.string.print_err));
        //从打印模块进去的，将直接退出界面
        if (mPresenter.isAutoPrint()) finish();
    }

    @Override
    public void setPrintingIndicator(boolean active) {
        if (active) {
            if (mDialogFragment == null) {
                mDialogFragment = new ProgressDialogFragment();
            }
            mDialogFragment.setTipTitle(getString(R.string.printing));
            mDialogFragment.setTip(getString(R.string.pls_wait));
            mDialogFragment.setCancelable(false);
            mDialogFragment.show(getSupportFragmentManager(), null);
        } else {
            if (mDialogFragment != null) {
                mDialogFragment.dismiss();
                mDialogFragment = null;
            }
        }
    }

    @Override
    public void showPrintSuccess() {
        //从打印模块进去的，将直接退出界面
        if (mPresenter.isAutoPrint()) finish();
    }

    @Override
    public void showPrintLackPaper() {
        TextDialogFragment dialogFragment = TextDialogFragment.newInstance();
        dialogFragment.setDialogType(TextDialogFragment.DIALOG_TYPE_WARNING);
        dialogFragment.setTitleText(getString(R.string.print_lack_paper));
        dialogFragment.setContentText(getString(R.string.print_lack_desc), Gravity.CENTER);
        dialogFragment.setPositionText(getString(R.string.confirm));
        dialogFragment.setNegativeText(getString(R.string.cancel));
        dialogFragment.setDialogListener(new TextDialogFragment.OnDialogListener() {
            @Override
            public void onCancel() {
                //从打印模块进去的，将直接退出界面
                if (mPresenter.isAutoPrint()) finish();
            }

            @Override
            public void onConfirm() {
                mPresenter.startPrint();
            }
        });
        dialogFragment.show(getSupportFragmentManager(), null);
    }

    @Override
    public void showConfirmPrintAgain() {
        //打印第一联完成后调用
        TextDialogFragment dialogFragment = TextDialogFragment.newInstance();
        dialogFragment.setDialogType(TextDialogFragment.DIALOG_TYPE_WARNING);
        dialogFragment.setTitleText(getString(R.string.kindly_tip));
        dialogFragment.setContentText(getString(R.string.continue_print), Gravity.CENTER);
        dialogFragment.setPositionText(getString(R.string.confirm), SysConstant.TIME_OUT_5);
        dialogFragment.setNegativeText(getString(R.string.cancel));
        dialogFragment.setDialogListener(new TextDialogFragment.OnDialogListener() {
            @Override
            public void onCancel() {
                showPrintSuccess();
            }

            @Override
            public void onConfirm() {
                mPresenter.startPrint();
            }
        });
        dialogFragment.show(getSupportFragmentManager(), null);
    }

    @Override
    public void showPrintFail(String failDesc) {
        if (!TextUtils.isEmpty(failDesc)){
            ToastUtils.showToast(failDesc);
        }
        //从打印模块进去的，将直接退出界面
        if (mPresenter.isAutoPrint()) finish();
    }

    @Override
    public void quitDetail() {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putBoolean(IS_CHANGE, mPresenter.getIsChange());
        intent.putExtras(bundle);
        setResult(RESP_CODE, intent);
        finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN){
            if(keyCode == KeyEvent.KEYCODE_BACK){
                quitDetail();
                return false;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 重打印最后一笔时，traceNm = null
     *
     * @param context
     * @return
     */
    public static Intent newInstance(Context context, String traceNum){
        Intent intent = new Intent(context, TransDetailActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString(TRACE_NUM, StringUtils.firstNonEmpty(traceNum, "000000"));
        intent.putExtras(bundle);
        return intent;
    }
    //wzp add 交易明细进来的隐藏撤销按钮
    public static Intent newInstance(Context context, String traceNum , boolean hideVoidBtn){
        Intent intent = new Intent(context, TransDetailActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString(TRACE_NUM, StringUtils.firstNonEmpty(traceNum, "000000"));
        bundle.putBoolean("hideVoidBtn",hideVoidBtn);
        intent.putExtras(bundle);
        return intent;
    }

    @Override
    public void finish() {
        super.finish();
        if (!mPresenter.isAutoPrint()){
            overridePendingTransition(R.anim.slide_left_in, R.anim.slide_right_out);
        }
    }
}
